<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-5-23
 * Time: 15:58
 */

namespace doumiaoduo\artdialog;


use yii\base\Widget;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

class ArtDialogIframe extends Widget{

    public $text='';

    public $url;

    public $dialogOptions=[];

    private $_rel_no;

    private $_defaultOptions=[
        'ok'=>"function(){
            var iframe = this.iframeNode.contentWindow;
            if (!iframe.document.body) {
                alert('iframe还没加载完毕呢');
                return false;
            };
            iframe.document.getElementById(\"dosubmit\").click();
            return false;
        }"
    ];

    public function init(){
        $this->_rel_no='artdialog_'.rand(10000000,99999999);
        foreach($this->_defaultOptions as $k=>$v){
            if(!isset($this->dialogOptions[$k])){
                $this->dialogOptions[$k]=$v;
            }
        }
    }

    public function run()
    {
        echo '<a rel="'.$this->_rel_no.'">'.$this->text.'</a>';
        $this->registerClientScript();
    }

    public function registerClientScript(){
        $view = $this->getView();
        ArtDialogAsset::register($view);
        $option=ArrayHelper::merge(['url'=>$this->url],$this->dialogOptions);
        $js_str="$(document).on('click','a[rel={$this->_rel_no}]',function(){ \n top.dialog({";
        $js_str.='min:false,max:false,lock:true,';
        foreach($option as $k=>$v){
            if($k=='title'||$k=='content'||$k=='url'||$k=='width'||$k=='height'||$k=='padding'){
                $js_str.="{$k}:'{$v}',\n";
            }
            else{
                $js_str.="{$k}:{$v},\n";
            }
        }
        $js_str.="}).showModal();});";
        $view->registerJs($js_str);
    }

}